package roma.lab1;

import java.util.ArrayList;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper extends SQLiteOpenHelper {

	public static final String DB_NAME = "LAB1";
	public static final String CURRENCY_TABLE = "exchangerate";
	public static final String CURRENCY_ID = "currencyId";
	public static final String CURRENCY_CODE = "currency";
	public static final String CURRENCY_RATE = "rate";
	private int rowsAffected = 0;

	public DatabaseHelper(Context context) {
		super(context, DB_NAME, null, 1);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub

		//db.execSQL("DROP TABLE IF EXISTS " + CURRENCY_TABLE);
		
		db.execSQL("CREATE TABLE " + CURRENCY_TABLE + " (" + CURRENCY_ID
				+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + CURRENCY_CODE
				+ " TEXT UNIQUE NOT NULL, " + CURRENCY_RATE + " NUMERIC)");

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

	public float getRate(String currency) {
		SQLiteDatabase db = this.getReadableDatabase();
		Cursor cursor = db.rawQuery("select rate from exchangerate where currency = ?", new String[]{ currency });

		cursor.moveToFirst();
		
		return cursor.getFloat(0);
	}

	public void addOrUpdateCurrency(String currency, float rate) {
		SQLiteDatabase db = this.getWritableDatabase();

		ContentValues values = new ContentValues();
		values.put(CURRENCY_CODE, currency);
		values.put(CURRENCY_RATE, rate);
		
		rowsAffected = db.update(CURRENCY_TABLE, values, CURRENCY_CODE + " = ?", new String[] { currency });
		if(rowsAffected == 0){
			db.insert(CURRENCY_TABLE, null, values);
		}
		rowsAffected = 0;
	}

	public ArrayList<String> getAllCurrencies() {
		SQLiteDatabase db = this.getReadableDatabase();
		ArrayList<String> currencies = new ArrayList<String>();

		Cursor c = db.query(CURRENCY_TABLE, new String[] { CURRENCY_CODE },
				null, null, null, null, CURRENCY_CODE);

		if (c.moveToFirst()) {
			do {
				currencies.add(c.getString(0));
			} while (c.moveToNext());
		}
		return currencies;
	}

}
